#include "stdafx.h"
#include "MD5.h"

string Hex2ASC(const byte *Hex, int Len)    
{    
	char *pASC = new char[Len * 2];
	memset(pASC,0,Len*2);
	int i;    

	for (i = 0; i < Len; i++)    
	{    
		pASC[i * 2] = "0123456789abcdef"[Hex[i] >> 4];    
		pASC[i * 2 + 1] = "0123456789abcdef"[Hex[i] & 0x0F];    
	}    

	string sRet(pASC,Len * 2);

	delete pASC;

	return sRet;    
}   

string MD5A(const  byte *pBuf,int nLen)
{
	PMD5Init MD5Init = NULL;    
	PMD5Update MD5Update = NULL;    
	PMD5Final MD5Final = NULL;    

	MD5_CTX ctx;    
	
	HINSTANCE hDLL;    

	if ( (hDLL = LoadLibrary(_T("Cryptdll.dll"))) > 0 )    
	{    

		MD5Init = (PMD5Init)GetProcAddress(hDLL,"MD5Init");    
		assert(MD5Init!=NULL);  
		MD5Update = (PMD5Update)GetProcAddress(hDLL,"MD5Update");  
		assert(MD5Update!=NULL);    
		MD5Final = (PMD5Final)GetProcAddress(hDLL,"MD5Final");    
		assert(MD5Final!=NULL);  

		MD5Init(&ctx);    
		MD5Update(&ctx,pBuf,nLen);    
		MD5Final(&ctx);    

		return Hex2ASC(ctx.digest,16);    

	}    
	  
	return "";
}

string MD5A(const  char *pBuf,int nLen)
{
	const  byte * pB = (const  byte *)pBuf;
	return MD5A(pB,nLen);
}